package com.livepass.android.girlspicks.activities;

/*
* Copyright 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/



import java.io.IOException;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.livepass.android.girlspicks.MyApplication;
import com.livepass.android.girlspicks.R;
import com.livepass.android.girlspicks.adapters.ArticleAdapter;
import com.livepass.android.girlspicks.utils.JSONParser;
import com.livepass.android.girlspicks.utils.Utilities;


/**
 * A simple launcher activity containing a summary sample description, sample log and a custom
 * {@link android.support.v4.app.Fragment} which can display a view.
 * <p>
 * For devices with displays with a width of 720dp or greater, the sample log is always visible,
 * on other devices it's visibility is controlled by an item on the Action Bar.
 */
public class TopViewActivity extends SampleActivityBase {

    public static final String TAG = "MainActivity";
    
    public ListView listArticle;
    public ArticleAdapter articleAdapter;
    private AsyncGetUserId loader;
    private AsyncGetNotifCount loaderNotif;
    ImageView imgMoring;
    ImageView imgEvening;
    TextView tvMoring;
    TextView tvEvening;
    TextView tvNoti;
    ImageView imgNoti;
    LinearLayout btnMorning;
    LinearLayout btnEvening;
    
    Calendar calendar;
    private int notifCount;
    private boolean isTouchImgNotif = false;
    
    //ActionBar actionBar;

    @SuppressWarnings("deprecation")
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_top_view);
        if(!Utilities.isNetworkAvailable(getApplicationContext())) {
			Toast.makeText(getApplicationContext(), "Can't connect to the network. Please try again!", Toast.LENGTH_SHORT).show();
			finish();
			return;
		}
        
        //initialize
        for(int i=1; i<10; i++) {
			MyApplication.NUMBER_OF_PAGES.put(String.valueOf(i), 1);
		}
        
        //get user id
        loader = new AsyncGetUserId();
        loader.execute();

        btnMorning = (LinearLayout) findViewById(R.id.btnMorning);
        btnEvening = (LinearLayout) findViewById(R.id.btnEvening);
        imgMoring = (ImageView) findViewById(R.id.imgMorning);
        imgEvening = (ImageView) findViewById(R.id.imgEvening);
        tvMoring = (TextView) findViewById(R.id.tvMorning);
        tvEvening = (TextView) findViewById(R.id.tvEvening);
        tvNoti = (TextView) findViewById(R.id.tvNoti);
        imgNoti = (ImageView) findViewById(R.id.imgNoti);
        
        calendar = Calendar.getInstance();
        
        //set morning or evening auto
        //morning
        if(calendar.getTime().getHours()>6 && calendar.getTime().getHours()<18) {
			btnMorning.setSelected(true);
			btnEvening.setSelected(false);
			MyApplication.AP = "1";
        } else { //evening
			btnMorning.setSelected(false);
			btnEvening.setSelected(true);
			MyApplication.AP = "2";
        }
        
        //click on Moring button or Evening button
        btnMorning.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				btnMorning.setSelected(true);
				btnEvening.setSelected(false);
				if(!"1".equals(MyApplication.AP)) {
					MyApplication.AP = "1";
					((SlidingTabsColorsFragment)getSupportFragmentManager().findFragmentById(R.id.sample_content_fragment)).changeMode(MyApplication.AP);
				}
			}
		});
		btnEvening.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnMorning.setSelected(false);
				btnEvening.setSelected(true);
				if(!"2".equals(MyApplication.AP)) {
					MyApplication.AP = "2";
					((SlidingTabsColorsFragment)getSupportFragmentManager().findFragmentById(R.id.sample_content_fragment)).changeMode(MyApplication.AP);
				}
				}
		});
		//reload notifications count when has not notif
		imgNoti.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				isTouchImgNotif = true;
				loaderNotif = new AsyncGetNotifCount();
		        loaderNotif.execute(MyApplication.USER_ID);
			}
		});
        
        //set Notification
        tvNoti.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intentNoti = new Intent(TopViewActivity.this, NotificationsActivity.class);
				intentNoti.putExtra("notif_count", notifCount);
				startActivity(intentNoti);
			}
		});
        
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        SlidingTabsColorsFragment fragment = new SlidingTabsColorsFragment();
        transaction.replace(R.id.sample_content_fragment, fragment);
        transaction.commit();
        
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	//set number of notification
    	if(loader != null) {
	        loaderNotif = new AsyncGetNotifCount();
	        loaderNotif.execute(MyApplication.USER_ID);
    	}
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode == MyApplication.COMMENT) {
			if (resultCode == RESULT_OK) {
				String cmtCountString = data.getStringExtra("cmt_count");
				((SlidingTabsColorsFragment)getSupportFragmentManager().findFragmentById(R.id.sample_content_fragment)).reloadCommentCountInListview(cmtCountString);
			}
    	}
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
    
	private class AsyncGetUserId extends AsyncTask<Void, Void, String> {

		String uuid = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
		
		@Override
		protected String doInBackground(Void... params) {

			String result = null;
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("device_id", uuid);
			//param.put("device_id", "1");

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest("http://girlspicks.co/api/user_access", param);
				JSONParser j = new JSONParser();
				result = j.parserUserId(jsonObject);
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
				return result;
			} catch (IOException e1) {
				e1.printStackTrace();
				return result;
			} catch (JSONException e) {
				e.printStackTrace();
				return result;
			}
			return result;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {

			if (result != null) {
				MyApplication.USER_ID = result;
		        //set number of notification
		        loaderNotif = new AsyncGetNotifCount();
		        loaderNotif.execute(MyApplication.USER_ID);
			} else {
				Toast.makeText(getApplicationContext(),
						"An unexpected error has occurred when get user id",
						Toast.LENGTH_SHORT).show();
				return;
			}
		}
	}
	
	private class AsyncGetNotifCount extends	AsyncTask<String, Void, Integer> {

		@Override
		protected Integer doInBackground(String... params) {
			int result = 0;
			Map<String, String> param = new LinkedHashMap<String, String>();
			param.put("id", "girlspicks");
			param.put("secret", "UCzCRQAAAIBVDBPwLuaV8o9mu");
			param.put("client_id", params[0]);

			JSONObject jsonObject = null;
			try {
				jsonObject = Utilities.doPostRequest("http://girlspicks.co/api/get_notif_count", param);
				result = jsonObject.getJSONArray("data").getJSONObject(0).getInt("notif_count");
			} catch (ClientProtocolException e1) {
				e1.printStackTrace();
				return result;
			} catch (IOException e1) {
				e1.printStackTrace();
				return result;
			} catch (JSONException e) {
				e.printStackTrace();
				return result;
			}
			return result;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(Integer result) {
			notifCount = result;

	        if (notifCount > 0) {
				tvNoti.setVisibility(View.VISIBLE);
				tvNoti.setText(""+notifCount);
			} else {
				tvNoti.setVisibility(View.GONE);
				if(isTouchImgNotif) {
					Toast.makeText(getApplicationContext(), "お知らせはありません。", Toast.LENGTH_SHORT).show();
				}
			}
			isTouchImgNotif = false;
		}
	}
}
